import React from "react";
import Table from 'antd/lib/table';
import Button from 'antd/lib/button';
import Divider from 'antd/lib/divider';
import Tag from 'antd/lib/tag';
import Select from 'antd/lib/select';
import Modal from 'antd/lib/modal';
import OrgUnit from "@/services/orgunit";
import CreateOrgUnitDialog from "@/components/orgstruct/OrgUnitDialog";
import {currentUser} from "@/services/auth";
import navigateTo from "@/components/ApplicationArea/navigateTo";
import Enums from "@/services/enums";
import notification from "@/services/notification";
import {get} from "lodash";
import WarningOutlined from "@ant-design/icons/WarningOutlined";

const { confirm } = Modal;

export default class OrgUnitTable extends React.Component {
  state = {
    orgunit_enum: 'all',
    data: [],
    selectedRowKeys: [],
    loading: true,
    currentPage: 1,
    total: 1,
    items:[],
  };

  componentWillMount() {
    Enums.items('orgunit_enum').then(data => {
      this.setState({
        items: data,
      });
      this.refreshData();
    });
  }

  refreshData(orgunit = 'all', pagination = 0) {
    ///if (orgunit === 'all') orgunit = this.state.orgunit_enum;
    if (pagination === 0) pagination = this.state.currentPage;
    // <Select.Option key="all" value=''>全部</Select.Option>
    // <Select.Option key="activate" value=''>启用</Select.Option>
    // <Select.Option key="noactivate" value=''>停用</Select.Option>
    OrgUnit.querylist({ orgunit_enum: orgunit, page: pagination })
      .then(({count, results}) => {
      this.setState({
        data: results,
        total: count,
        orgunit_enum: orgunit,
        currentPage: pagination,
        loading: false,
      });
    });
  }

  onSelectChange = selectedRowKeys => {
    this.setState({ selectedRowKeys });
  };

  unitSelectChange = value => {
    this.refreshData(value,1);
  };

  handleTableChange = pagination => {
    this.refreshData('',pagination);
  };

  handleUpdate = record => {
    const orgunit_id = record.id;
    this.showCreateOrgUnitDialog(orgunit_id);
  };

  handleDelete = record => {
    confirm({
      title: '确定删除部门?',
      icon: <WarningOutlined />,
      content: record.name,
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      onOk: () => {
        OrgUnit.delete(record).then(()=>{
          notification.success("部门删除成功.");
          this.refreshData('',1);
        }).catch(error => {
          notification.error(get(error, "response.data.message", "删除失败."));
        });
      },
    });
  };

  handleActive = record => {
    const tip = record.is_active ? "确定停用部门?" : "确定启用部门?";
    confirm({
      title: tip,
      icon: <WarningOutlined />,
      content: record.name,
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      onOk:() => {
        OrgUnit.active(record).then(()=>{
          notification.success("部门启用/停用操作成功.");
          this.refreshData('',0);
        });
      },
    });
  };

  handleStart = () => {
    OrgUnit.select(this.props.orgstruct_id, JSON.stringify(this.state.selectedRowKeys)).then(()=>{
      notification.success("成功选取部门至部门.");
      this.props.selectChange();
      this.setState({ selectedRowKeys:[] });
    });
  };


  renderUnitSelect(){
    return (
      <Select style={{ width: 120 }} value={this.state.orgunit_enum} onChange={(value) => this.unitSelectChange(value)}>
        <Select.Option key="all" value='all'>全部</Select.Option>
        <Select.Option key="activate" value='activate'>启用</Select.Option>
        <Select.Option key="noactivate" value='noactivate'>停用</Select.Option>
        {/* {this.state.items.map(item => (
          <Select.Option key={item.value} value={item.value}>{item.label}</Select.Option>
        ))} */}
      </Select>
    );
  };

  showCreateOrgUnitDialog = (id) => {
    CreateOrgUnitDialog.showModal({orgunit_id: id})
    .onClose((result = {}) => {
        if (result.success) {
          this.refreshData();
        }
      }).onDismiss(() => {
        navigateTo("orgstruct", true);
      });
  };

  render() {
    if (this.state.loading) return null;

    const columns = [
      {
        title: '部门名称',
        dataIndex: 'name',
        key: 'name',
        render: (text, record) => (
          <a className="clickable" onClick={() => this.handleUpdate(record)}>{text}</a>
      ),
      },
      {
        title: '简称',
        key: 'shortname',
        dataIndex: 'shortname',
      },
      // {
      //   title: '编码',
      //   dataIndex: 'code',
      //   key: 'code',
      // },
      {
        title: '所属单元类型',
        key: 'orgunit_enums',
        dataIndex: 'orgunit_enums',
        render: tags => (
          <span>
            {tags.map(tag => {
              return (
                <Tag>{tag}</Tag>
              );
            })}
          </span>
        ),
      },
      {
        title: '操作',
        key: 'action',
        render: (record) => (
          <span>
            <a className="clickable" onClick={() => this.handleActive(record)}>
              {record.is_active ? "停用" : "启用"}
            </a>
            <Divider type="vertical" />
            <a className="clickable" onClick={() => this.handleDelete(record)}>删除</a>
          </span>
        ),
      },
    ];

    const paginationProps = {
      page: this.state.currentPage,
      onChange : (page) => this.handleTableChange(page),
      total: this.state.total,
    }

    const rowSelection = {
      selectedRowKeys: this.state.selectedRowKeys,
      onChange: this.onSelectChange,
    };
    const hasSelected = this.state.selectedRowKeys.length > 0;

    return(
      <div>
        <div style={{ marginBottom: 16 }}>
        {(currentUser.isAdmin && this.props.orgstruct_id !== 0) && (
          <Button type="primary" onClick={this.handleStart} disabled={!hasSelected}>
            <i className="fa fa-plus m-r-5" />
            加入部门
          </Button>
        )}
          <span style={{ marginLeft: 8 }}>
            状态：
          </span>
          {this.renderUnitSelect()}
        {(currentUser.isAdmin || currentUser.isDefault) && (
          <Button type="primary" onClick={() => this.showCreateOrgUnitDialog(0)}>
            <i className="fa fa-plus m-r-5" />
            新建部门
          </Button>
        )}
        </div>
        <Table rowKey='id' rowSelection={rowSelection} columns={columns} dataSource={this.state.data} pagination={paginationProps} />
      </div>
    );
  };
}

